package com.example.customview.view

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.TypeEvaluator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Shader
import android.util.AttributeSet
import android.view.View
import android.view.animation.DecelerateInterpolator
import androidx.core.graphics.toColorInt
import com.example.customview.R
import com.sample.base.utils.dp

@SuppressLint("NewApi")
class ZProgressView(context: Context, attrs: AttributeSet?) : View(context, attrs) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val fontMetrics = Paint.FontMetrics()
    private val maxProgress = 100
    private var progressDirection = 0
    private var progressColor = resources.getColor(R.color.colorMaiMiaolv, resources.newTheme())
    private var progressBgColor = resources.getColor(R.color.colorGrey, resources.newTheme())
    private var progressCenterCircleBgColor =
        resources.getColor(R.color.colorGrey, resources.newTheme())
    private var progressWidth = 20.dp.toFloat()
    private var circleSpace = 12.dp.toFloat()
    private var progressTextColor = resources.getColor(R.color.colorWhite, resources.newTheme())
    private var progressTextSize = 20.dp.toFloat()
    var linearGradient: LinearGradient? = null
    private var needGradientBg = true

    init {
        val array = context.obtainStyledAttributes(attrs, R.styleable.ZProgressView)
        progressColor = array.getColor(R.styleable.ZProgressView_zprogressColor, progressColor)
        progressCenterCircleBgColor = array.getColor(
            R.styleable.ZProgressView_zprogressCenterCircleColor,
            progressCenterCircleBgColor
        )
        progressBgColor =
            array.getColor(R.styleable.ZProgressView_zprogressBgColor, progressBgColor)
        progressWidth = array.getDimension(R.styleable.ZProgressView_zprogressWidth, progressWidth)
        circleSpace =
            array.getDimension(R.styleable.ZProgressView_zprogressCircleSpace, circleSpace)
        progressTextColor =
            array.getColor(R.styleable.ZProgressView_zprogressTextColor, progressTextColor)
        progressTextSize =
            array.getDimension(R.styleable.ZProgressView_zprogressTextSize, progressTextSize)
        progressDirection =
            array.getInt(R.styleable.ZProgressView_zprogressDirection, progressDirection)
        array.recycle()
    }

    var progress: Float = 0f
        set(value) {
            field = value
            invalidate()
        }

    var progressText = 0
        set(value) {
            field = value
            invalidate()
        }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        if (needGradientBg) {
            // 先定义成固定的值，目前已满足当前项目要求，后续需要扩展的时候再提出来
            val colorStart = "#FFDA44".toColorInt()
            val colorEnd = "#FF8800".toColorInt()
            val gradientColors = intArrayOf(colorStart, colorEnd)
            val gradientPosition = floatArrayOf(0.2f, 0.8f)
            linearGradient = LinearGradient(
                0f,
                0f,
                0f,
                height.toFloat(),
                gradientColors, gradientPosition,
                Shader.TileMode.CLAMP
            )
        }

    }

    override fun onDraw(canvas: Canvas) {
        // 绘制中心背景圆
        paint.style = Paint.Style.FILL
        if (needGradientBg) {
            paint.shader = linearGradient
        } else {
            paint.color = progressCenterCircleBgColor
        }
        canvas.drawCircle(
            width / 2f,
            height / 2f,
            (width / 2f - progressWidth - circleSpace),
            paint
        )
        if (needGradientBg) {
            paint.shader = null
        }

        // 绘制进度条背景圆环
        paint.style = Paint.Style.STROKE
        paint.color = progressBgColor
        paint.strokeWidth = progressWidth.toFloat()
        canvas.drawCircle(width / 2f, height / 2f, (width - progressWidth.toFloat()) / 2f, paint)

        //绘制进度条
        paint.color = progressColor
        paint.strokeCap = Paint.Cap.ROUND
        canvas.drawArc(
            progressWidth / 2f,
            progressWidth / 2f,
            width.toFloat() - progressWidth / 2f,
            height.toFloat() - progressWidth / 2f,
            -90f,
            if (0 == progressDirection)
                360f * progress / maxProgress else -(360f * progress / maxProgress),
            false,
            paint
        )

        // 绘制中间的文字
        paint.style = Paint.Style.FILL
        paint.color = progressTextColor
        paint.textSize = progressTextSize
        paint.textAlign = Paint.Align.CENTER
        paint.getFontMetrics(fontMetrics)
        canvas.drawText(
            progressText.toString(),
            width / 2f,
            height / 2f - (fontMetrics.ascent + fontMetrics.descent) / 2f,
            paint
        )
    }

    /**
     * 需要使用动画效果就调用这个方法进行属性设置
     * @param progress 进度
     * @param progressText 圆弧中心的文字
     */
    fun setProgressWithAnimator(progress: Float, progressText: Int) {
        val progressAnimator = ObjectAnimator.ofFloat(
            this, "progress",
            0f, progress
        )
        val textAnimator = ObjectAnimator.ofObject(
            this, "progressText",
            TypeEvaluator<Int> { fraction, startValue, endValue ->
                startValue + ((endValue - startValue) * fraction).toInt()
            },
            0, progressText
        )
        val animatorSet = AnimatorSet().apply {
            play(progressAnimator).with(textAnimator)
            startDelay = 1000
            duration = 3000
            interpolator = DecelerateInterpolator()
        }
        animatorSet.start()
    }
}